package com.hunter.view;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import com.hunter.util.SystemUtil;
import com.mkk.swing.SwingUtil;
import com.mkk.swing.SwingUtil.UIType;

/**
 * 2010-8-16 下午08:06:06 <br>
 * 系统设置界面,内容包括:
 * <ul>
 * <li>索引创建</li>
 * <li>搜索设置</li>
 * <li>初始设置</li>
 * </ul>
 * 
 * @author mkk
 */
public class SettingDialog extends JDialog {

	private static final long serialVersionUID = 1L;
	// 默认大小
	private static int DEFAULT_WIDTH = 610;
	private static int DEFAULT_HEIGHT = 490;
	// card names
	public static final String CARD_CREATE_INDEX = "createIndex";
	public static final String CARD_INDEX_MANAGE = "indexManage";
	public static final String CARD_SEARCH_SET = "searchSet";
	public static final String CARD_INIT_SET = "initSet";
	public static final String CARD_MANAGE_INDEX = "manIndex";
	public static final String CARD_DEFAULT_SEARCH_SET="defaultSearchset";
	public static final String CARD_PERSONAL_SET="personalSet";
	public static final String CARD_DEFAULT_SUFFIX="defaultSuffix";
	public static final String CARD_GRAPHICS_SET="graphicsSet";
	// 标题
	private String title = "设置";
	// 面板
	private JPanel panel1, panel2, panel3, panel4;
	// 标签
	private JLabel label1;
	// 按钮
	private JButton button1, button2, button3;
	// splitpane
	private JSplitPane splitPane;
	// tree
	private JTree tree;
	// treemodel
	private DefaultTreeModel defaultTreeModel;
	// search field
	private JTextField textField1;
	// card layout
	private CardLayout cardLayout;
	// other panels
	private IndexsManagePanel indexManPanel;
	private CreateIndexPanel createIndexPanel;
	private SearchSetPanel searchSetPanel;
	private InitSetPanel initSetPanel;
	private IndexsManPanel indexMangePanel;
	private DefaultSearchSetPanel defaultSearchSet;
	private PersonalSetPanel personalSet;
	private DefaultSuffixPanel defaultSuffexPanel;
	private GraphicsSetPanel graphicsSetPanel;
	// 搜索延迟时间值
	private int delay = 300;

	/**
	 * 构造器
	 * 
	 * @param parent
	 *            父组件
	 * @param model
	 *            是否模式
	 */
	public SettingDialog(JFrame parent, boolean model) {
		super(parent, model);
		this.initCompents();
		this.processEvents();
	}

	/**
	 * 初始化组件
	 */
	private void initCompents() {
		this.setTitle(title);
		this.setIconImage(SystemUtil.getSystemLogoIcon().getImage());
		this.setLayout(new BorderLayout(5, 5));
		this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.initCenterPanel();
		this.add(panel1, BorderLayout.CENTER);
		this.initSouthPanel();
		this.add(panel2, BorderLayout.SOUTH);
	}

	/**
	 * 初始化中部面板
	 */
	private void initCenterPanel() {
		this.panel1 = new JPanel();
		this.panel1.setLayout(new BorderLayout());
		panel3 = new JPanel();
		panel4 = new JPanel();
		// right panel
		cardLayout = new CardLayout();
		panel4.setLayout(cardLayout);
		this.indexManPanel = new IndexsManagePanel(this);
		panel4.add(indexManPanel, CARD_INDEX_MANAGE);
		// panel4.add(new CreateIndexPanel(this), CARD_CREATE_INDEX);
		this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel3,
				panel4);
		this.splitPane.setDividerLocation(130);
		splitPane.setDividerSize(2);
		panel1.add(this.splitPane, BorderLayout.CENTER);
		// treemodel
		this.defaultTreeModel = new DefaultTreeModel(this.getTreeNode());
		this.defaultTreeModel.setAsksAllowsChildren(true);
		this.tree = new JTree(defaultTreeModel);
		// set icon
		DefaultTreeCellRenderer render = new DefaultTreeCellRenderer();
		render.setOpenIcon(SystemUtil.getIcon("1.gif"));
		render.setClosedIcon(SystemUtil.getIcon("2.gif"));
		render.setLeafIcon(SystemUtil.getIcon("null.gif"));
		this.tree.setCellRenderer(render);
		// single select
		TreeSelectionModel sModel = new DefaultTreeSelectionModel();
		sModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		this.tree.setSelectionModel(sModel);
		tree.setRootVisible(false);
		panel3.setLayout(new BorderLayout());
		panel3.add(new JScrollPane(tree), BorderLayout.CENTER);
		textField1 = new JTextField(22);
		textField1.setText("搜索");
		textField1.setForeground(Color.LIGHT_GRAY);
		textField1.selectAll();
		panel3.add(textField1, BorderLayout.NORTH);
	}

	/**
	 * @return the cardLayout
	 */
	public CardLayout getCardLayout() {
		return cardLayout;
	}

	/**
	 * 南部面板
	 */
	private void initSouthPanel() {
		this.panel2 = new JPanel();
		this.panel2.setLayout(new GridBagLayout());
		// help
		this.button3 = new JButton(SystemUtil.getIcon("help.gif"));
		button3.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5));
		GridBagConstraints cons1 = new GridBagConstraints();
		cons1.weightx = button3.getWidth();
		cons1.weighty = 20;
		cons1.gridx = 0;
		cons1.gridy = 0;
		cons1.gridwidth = 1;
		cons1.gridheight = 1;
		this.panel2.add(button3, cons1);
		// status
		this.label1 = new JLabel();
		label1.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints cons2 = new GridBagConstraints();
		cons2.weightx = 100;
		cons2.weighty = 30;
		cons2.gridx = 1;
		cons2.gridy = 0;
		cons2.gridwidth = 5;
		cons2.gridheight = 1;
		this.panel2.add(label1, cons2);
		this.button2 = new JButton("确定");
		GridBagConstraints cons3 = new GridBagConstraints();
		cons3.weightx = button2.getWidth();
		cons3.weighty = 20;
		cons3.gridx = 6;
		cons3.gridy = 0;
		cons3.gridwidth = 1;
		cons3.gridheight = 1;
		this.panel2.add(button2, cons3);
		this.button1 = new JButton("取消");
		GridBagConstraints cons4 = new GridBagConstraints();
		cons4.weightx = button1.getWidth() + 5;
		cons4.weighty = 20;
		cons4.gridx = 7;
		cons4.gridy = 0;
		cons4.gridwidth = 1;
		cons4.gridheight = 1;
		this.panel2.add(button1, cons4);
	}

	/**
	 * @return the panel4
	 */
	public JPanel getPanel4() {
		return panel4;
	}

	/**
	 * 获取树信息
	 * 
	 * @return
	 */
	private DefaultMutableTreeNode getTreeNode() {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
		DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("索引管理");
		DefaultMutableTreeNode node11 = new DefaultMutableTreeNode("创建索引");
		node11.setAllowsChildren(false);
		DefaultMutableTreeNode node12 = new DefaultMutableTreeNode("管理创建的索引");
		node12.setAllowsChildren(false);
		node1.add(node11);
		node1.add(node12);
		DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("搜索设置");
		DefaultMutableTreeNode node21 = new DefaultMutableTreeNode("默认搜索");
		DefaultMutableTreeNode node22 = new DefaultMutableTreeNode("个人爱好");
		node21.setAllowsChildren(false);
		node22.setAllowsChildren(false);
		node2.add(node21);
		node2.add(node22);
		DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("初始设置");
		DefaultMutableTreeNode node31 = new DefaultMutableTreeNode("默认后缀名");
		DefaultMutableTreeNode node32 = new DefaultMutableTreeNode("界面设置");
		//DefaultMutableTreeNode node33 = new DefaultMutableTreeNode("索引文件");
		node31.setAllowsChildren(false);
		node32.setAllowsChildren(false);
		//node33.setAllowsChildren(false);
		node3.add(node31);
		node3.add(node32);
		//node3.add(node33);
		root.add(node1);
		root.add(node2);
		root.add(node3);
		return root;
	}

	/**
	 * 事件处理
	 */
	private void processEvents() {
		// 确定事件
		this.button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 目前与取消一样
				SettingDialog.this.dispose();
			}
		});
		// 关闭事件
		this.button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SettingDialog.this.dispose();
			}
		});
		// 帮助事件
		this.button3.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				SwingUtil.showSimpleNormalInfo("Help");

			}
		});
		// 搜索框焦点事件
		this.textField1.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent e) {
				String s = textField1.getText().trim();
				if (s.length() > 0) {
					textField1.selectAll();
				}
			}
		});
		// 搜索框搜索事件
		this.textField1.getDocument().addDocumentListener(
				new DocumentListener() {
					public void removeUpdate(DocumentEvent e) {
						searchTree();
					}

					public void insertUpdate(DocumentEvent e) {
						searchTree();
					}

					public void changedUpdate(DocumentEvent e) {
					}
				});
		// 树点击事件
		this.tree.addMouseListener(new MouseAdapter() {

			public void mousePressed(MouseEvent e) {
				int selRow = tree.getRowForLocation(e.getX(), e.getY());
				TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
				if (selRow == -1) {
					return;
				}
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selPath
						.getLastPathComponent();
				int count = e.getClickCount();
				if (count == 2) {
					// 双击展开
					tree.makeVisible(selPath);
					tree.scrollPathToVisible(selPath);
				} else if (count == 1) {
					// 单击
					tree.setSelectionPath(selPath);
					String obj = (String) parent.getUserObject();
					// 显示对应的界面
					showAssignPanel(obj);
				}

			}
		});
	}

	/**
	 * 显示指定的树节点
	 * 
	 * @param nodeName
	 *            节点名称,如 索引管理节点
	 */
	public void showTreeNode(String nodeName) {
		DefaultMutableTreeNode node = this.findUserObject(nodeName);
		if (node == null) {
			return;
		}
		TreeNode tn[]=defaultTreeModel.getPathToRoot(node);
		TreePath path = new TreePath(tn);
		tree.setSelectionPath(path);
		tree.makeVisible(path);
		tree.scrollPathToVisible(path);
	}

	/**
	 * 搜索树节点
	 */
	private void searchTree() {
		final String s = textField1.getText().trim();
		if (s.length() <= 0) {
			return;
		}
		ActionListener action = new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				DefaultMutableTreeNode root = (DefaultMutableTreeNode) defaultTreeModel
						.getRoot();
				List<DefaultMutableTreeNode> list = findUserObject(root, s);
				TreeNode[] nods = null;
				if (list.size() > 0) {
					TreePath[] tps = new TreePath[list.size()];
					int i = 0;
					for (DefaultMutableTreeNode dtdn : list) {
						nods = defaultTreeModel.getPathToRoot(dtdn);
						TreePath path = new TreePath(nods);
						tps[i++] = path;
					}
					// 显示
					tree.setSelectionPaths(tps);
					tree.makeVisible(tps[0]);
					tree.scrollPathToVisible(tps[0]);
				} else {
					defaultTreeModel.reload();
				}
			}
		};
		Timer timer = new Timer(delay, action);
		timer.setRepeats(false);
		timer.start();
	}

	/**
	 * 根据关键字查找相应的DefaultMutableTreeNode
	 * 
	 * @param root
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<DefaultMutableTreeNode> findUserObject(
			DefaultMutableTreeNode root, String key) {
		List<DefaultMutableTreeNode> list = new ArrayList<DefaultMutableTreeNode>();
		Enumeration enume = root.breadthFirstEnumeration();
		while (enume.hasMoreElements()) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) enume
					.nextElement();
			if (node.getUserObject().toString().toLowerCase().contains(key)) {
				list.add(node);
			}
		}
		return list;
	}

	/**
	 * 根据关键字查找相应的DefaultMutableTreeNode
	 * 
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private DefaultMutableTreeNode findUserObject(String key) {
		DefaultMutableTreeNode root = (DefaultMutableTreeNode) defaultTreeModel
				.getRoot();
		Enumeration enume = root.breadthFirstEnumeration();
		while (enume.hasMoreElements()) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) enume
					.nextElement();
			if (node.getUserObject().toString().toLowerCase().contains(key)) {
				return node;
			}
		}
		return null;
	}

	/**
	 * 显示指定的界面,用于树的点击事件
	 * 
	 * @param panelName
	 */
	private void showAssignPanel(final String panelName) {
		new Thread() {
			public void run() {
				if ("索引管理".equals(panelName)) {
					// 索引管理
					showPanel(CARD_INDEX_MANAGE);
				} else if ("创建索引".equals(panelName)) {
					// 创建索引
					showPanel(CARD_CREATE_INDEX);
				} else if ("搜索设置".equals(panelName)) {
					// 搜索设置
					showPanel(CARD_SEARCH_SET);
				} else if ("初始设置".equals(panelName)) {
					// 初始设置
					showPanel(CARD_INIT_SET);
				} else if ("管理创建的索引".equals(panelName)) {
					// 管理创建的索引
					showPanel(CARD_MANAGE_INDEX);
				}else if("个人爱好".equals(panelName)) {
					showPanel(CARD_PERSONAL_SET);
				}else if("默认搜索".equals(panelName)) {
					showPanel(CARD_DEFAULT_SEARCH_SET);
				}else if("默认后缀名".equals(panelName)) {
					showPanel(CARD_DEFAULT_SUFFIX);
				}else if("界面设置".equals(panelName)) {
					showPanel(CARD_GRAPHICS_SET);
				}
				// more else if
			}
		}.start();

	}

	/**
	 * cardLayout 管理的界面跳转方法
	 * 
	 * @param panelName
	 *            必须是以CARD_开头的静态变量之一
	 */
	public void showPanel(String panelName) {
		if (CARD_CREATE_INDEX.equals(panelName)) {
			// 创建索引
			if (createIndexPanel == null) {
				createIndexPanel = new CreateIndexPanel(SettingDialog.this);
				panel4.add(createIndexPanel, CARD_CREATE_INDEX);
			}
			cardLayout.show(panel4, CARD_CREATE_INDEX);
		} else if (CARD_INDEX_MANAGE.equals(panelName)) {
			// 索引管理
			if (indexManPanel == null) {
				indexManPanel = new IndexsManagePanel(SettingDialog.this);
				panel4.add(indexManPanel, CARD_INDEX_MANAGE);
			}
			cardLayout.show(panel4, CARD_INDEX_MANAGE);
		} else if (CARD_INIT_SET.equals(panelName)) {
			// 初始设置
			if (initSetPanel == null) {
				initSetPanel = new InitSetPanel(SettingDialog.this);
				panel4.add(initSetPanel, CARD_INIT_SET);
			}
			cardLayout.show(panel4, CARD_INIT_SET);
		} else if (CARD_SEARCH_SET.equals(panelName)) {
			// 搜索设置
			if (searchSetPanel == null) {
				searchSetPanel = new SearchSetPanel(SettingDialog.this);
				panel4.add(searchSetPanel, CARD_SEARCH_SET);
			}
			cardLayout.show(panel4, CARD_SEARCH_SET);
		} else if (CARD_MANAGE_INDEX.equals(panelName)) {
			// 管理已创建的索引
			if (this.indexMangePanel == null) {
				this.indexMangePanel = new IndexsManPanel(this);
				panel4.add(this.indexMangePanel, CARD_MANAGE_INDEX);
			}
			cardLayout.show(panel4, CARD_MANAGE_INDEX);
		}else if(CARD_DEFAULT_SEARCH_SET.equals(panelName)) {
			//默认搜索设置
			if(this.defaultSearchSet==null) {
				this.defaultSearchSet=new DefaultSearchSetPanel(this);
				panel4.add(this.defaultSearchSet,CARD_DEFAULT_SEARCH_SET);
			}
			cardLayout.show(panel4, CARD_DEFAULT_SEARCH_SET);
		}else if(CARD_PERSONAL_SET.equals(panelName)) {
			//个人爱好
			if(this.personalSet==null) {
				this.personalSet=new PersonalSetPanel(this);
				panel4.add(this.personalSet,CARD_PERSONAL_SET);
			}
			cardLayout.show(panel4, CARD_PERSONAL_SET);
		}else if(CARD_DEFAULT_SUFFIX.equals(panelName)) {
			//默认后缀名
			if(this.defaultSuffexPanel==null) {
				this.defaultSuffexPanel=new DefaultSuffixPanel(this);
				panel4.add(this.defaultSuffexPanel,CARD_DEFAULT_SUFFIX);
			}
			cardLayout.show(panel4, CARD_DEFAULT_SUFFIX);
		}else if(CARD_GRAPHICS_SET.equals(panelName)) {
			//界面设置
			if(this.graphicsSetPanel==null) {
				this.graphicsSetPanel=new GraphicsSetPanel(this);
				panel4.add(this.graphicsSetPanel,CARD_GRAPHICS_SET);
			}
			cardLayout.show(panel4, CARD_GRAPHICS_SET);
		}
		// more else if
	}

	/**
	 * 设置状态栏信息
	 * 
	 * @param info
	 * @param c
	 */
	void setInfo(String info, Color c) {
		this.label1.setText(info);
		this.label1.setForeground(c);
	}

	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				SwingUtil.setUI(UIType.WINDOWS);
				SettingDialog dialog = new SettingDialog(
						new javax.swing.JFrame(), true);
				dialog.setLocation(300, 200);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {
					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

}
